package com.tbl.modules.wms2.controller.production;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONTokener;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.fasterxml.jackson.core.JsonParser;
import com.google.gson.JsonObject;
import com.tbl.common.utils.StringUtils;
import com.tbl.modules.platform.constant.MenuConstant;
import com.tbl.modules.platform.controller.AbstractController;
import com.tbl.modules.platform.service.system.RoleService;
import com.tbl.modules.wms.dao.baseinfo.WarehouseDAO;
import com.tbl.modules.wms.dao.interfacelog.InterfaceLogDAO;
import com.tbl.modules.wms.entity.baseinfo.Warehouse;
import com.tbl.modules.wms2.constant.Constant;
import com.tbl.modules.wms2.controller.insidewarehouse.TransferOrderController;
import com.tbl.modules.wms2.controller.material.MaterialBackController;
import com.tbl.modules.wms2.controller.operation.YclInOutFlowController;
import com.tbl.modules.wms2.dao.insidewarehouse.transferorder.TransferOrderDAO;
import com.tbl.modules.wms2.dao.insidewarehouse.transferorder.TransferOrderLineDAO;
import com.tbl.modules.wms2.dao.production.ProdPickingDAO;
import com.tbl.modules.wms2.dao.production.YclMeterialOutDAO;
import com.tbl.modules.wms2.entity.baseinfo.PickingOutDealEntity;
import com.tbl.modules.wms2.entity.baseinfo.PickingOutItemEntity;
import com.tbl.modules.wms2.entity.insidewarehouse.transferorder.TransferOrderEntity;
import com.tbl.modules.wms2.entity.insidewarehouse.transferorder.TransferOrderLineEntity;
import com.tbl.modules.wms2.entity.production.*;
import com.tbl.modules.wms2.entity.purchasein.MeteriaRcvEbsEntity;
import com.tbl.modules.wms2.service.baseinfo.MesService;
import com.tbl.modules.wms2.service.common.CountService;
import com.tbl.modules.wms2.service.insidewarehouse.transferorder.TransferOrderLineService;
import com.tbl.modules.wms2.service.operation.YclInOutFlowService;
import com.tbl.modules.wms2.service.production.ProdPickingService;
//import net.sf.json.JSONObject;
import net.sf.json.JSONArray;
import org.apache.shiro.session.mgt.DelegatingSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.tbl.modules.wms2.entity.operation.YclInOutFlowEntity;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 生产领料
 *
 * @author DASH
 */
@Controller
@RequestMapping(value = "/ycl/production/picking")
public class ProdPickingController extends AbstractController {


    @Autowired
    private RoleService roleService;

    @Autowired
    private ProdPickingService prodPickingService;

    @Autowired
    private ProdPickingDAO prodPickingDAO;

    @Autowired
    private YclMeterialOutDAO yclMeterialOutDAO;

    @Autowired
    private YclInOutFlowController yclInOutFlowController;

    @Autowired
    private CountService countService;

    @Autowired
    private MaterialBackController materialBackController;

    @Autowired
    private MesService mesService;

    @Resource
    private WarehouseDAO warehouseDAO;

    @Autowired
    private TransferOrderDAO transferOrderDAO;

    @Autowired
    private TransferOrderLineService transferOrderLineService;

    @Autowired
    private TransferOrderController transferOrderController;

    @Autowired
    private YclInOutFlowService yclInOutFlowService;

    /**
     * 保存
     *
     * @param
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    @Transactional
    public Map<String, Object> save(@RequestBody List<Map> list) {
        Map<String, Object> ret_map = new HashMap<>(2);
        List<YclMaterialOutEntity> yclMaterialOutEntityList = new ArrayList<>();

        String seq_no = countService.getNextCount("SCLL");

        DateTime now_time = DateUtil.date();

        try {
            for (Map map : list) {
                int count = prodPickingDAO.getCountByLineId(String.valueOf(map.get("lineId")));

                if (count > 0) {
                    ret_map.put("result", false);
                    ret_map.put("msg", "该领料单已出库，请勿重复出库");
                    return ret_map;
                }

                String lots_Num = map.get("lotsNum").toString();
                lots_Num = lots_Num.split(",")[0];

                //获取tolocatorID
                Map<String, Object> storeMap = new HashMap();
                storeMap.put("factorycode", Long.parseLong(map.get("organizationId").toString()));
                storeMap.put("code", (String) map.get("fromSubinvCode"));
                Warehouse warehouseDto = warehouseDAO.getWarehouseByCode(storeMap);
                if (warehouseDto == null) {
                    ret_map.put("result", false);
                    ret_map.put("msg", "没有配置EBS库位");
                    return ret_map;
                }

                String locatorld = warehouseDto.getLocatorId() == null ? "" : warehouseDto.getLocatorId().toString();

                MeteriaRcvEbsEntity meteriaRcvEbsEntity = new MeteriaRcvEbsEntity();
                meteriaRcvEbsEntity.setHeaderId(Long.parseLong(map.get("headerId").toString()));
                meteriaRcvEbsEntity.setLineId(Long.parseLong(map.get("lineId").toString()));
                meteriaRcvEbsEntity.setOrgId(Long.parseLong(map.get("organizationId").toString()));
                meteriaRcvEbsEntity.setVendorLot(lots_Num);
                meteriaRcvEbsEntity.setTransactionDate(DateUtil.format(DateUtil.date(), "yyyy-MM-dd"));
                meteriaRcvEbsEntity.setTransactionQuantity(new BigDecimal((String) map.get("outQuantity")));
                meteriaRcvEbsEntity.setComments(null == map.get("comments") ? "" : map.get("comments").toString());
                meteriaRcvEbsEntity.setVendorName("");
                meteriaRcvEbsEntity.setFromLocatorId(Long.parseLong(locatorld));
                meteriaRcvEbsEntity.setToLocatorId(Long.parseLong(locatorld));
                Map<String, Object> retMap = materialBackController.materialReceiveEBS(meteriaRcvEbsEntity);
                if (Constant.ERROR.equals(retMap.get("retCode"))) {
                    ret_map.put("result", false);
                    ret_map.put("msg", retMap.get("retMess").toString());
                    return ret_map;
                }

                Map<String, Object> param_map = new HashMap<>();

                param_map.put("organizationId", Long.parseLong(map.get("organizationId").toString()));
                param_map.put("headerId", Long.parseLong(map.get("headerId").toString()));
                param_map.put("lineId", Long.parseLong(map.get("lineId").toString()));
                param_map.put("materialCode", (String) map.get("itemCode"));
                param_map.put("lotsNum", lots_Num);
                param_map.put("quantity", Long.parseLong(map.get("outQuantity").toString()));
                param_map.put("operator", this.getSessionUser().getUsername());
                param_map.put("transDate", new Date());
                param_map.put("comments", null == map.get("comments") ? "" : map.get("comments").toString());

                mesService.issueBillLot(param_map);

                if (Constant.ERROR.equals(param_map.get("retCode"))) {
                    ret_map.put("result", false);
                    ret_map.put("msg", param_map.get("retMess").toString());
                    return ret_map;
                }

                YclMaterialOutEntity yclMaterialOutEntity = new YclMaterialOutEntity();
                yclMaterialOutEntity.setOutCode(seq_no);
                yclMaterialOutEntity.setLineId(String.valueOf(map.get("lineId")));
                yclMaterialOutEntity.setAreaCode(String.valueOf(map.get("organizationId")));
                yclMaterialOutEntity.setStoreCode((String) map.get("fromSubinvCode"));
                yclMaterialOutEntity.setLocatorCode((String) map.get("locatorCode"));
                yclMaterialOutEntity.setApplyCode((String) map.get("moCode"));
                yclMaterialOutEntity.setLineCode(String.valueOf(map.get("lineNum")));
                yclMaterialOutEntity.setMaterialCode((String) map.get("itemCode"));
                yclMaterialOutEntity.setMaterialName((String) map.get("itemDesc"));
                yclMaterialOutEntity.setPrimaryUnit((String) map.get("primaryUomCode"));
                yclMaterialOutEntity.setLotsNum(lots_Num);
                yclMaterialOutEntity.setShift((String) map.get("shiftCode"));
                yclMaterialOutEntity.setDevice((String) map.get("deviceCode"));
                yclMaterialOutEntity.setQuantity(map.get("quantity").toString());
                yclMaterialOutEntity.setOutQuantity((String) map.get("outQuantity"));
                yclMaterialOutEntity.setState("1");
                yclMaterialOutEntity.setCreateUser(this.getSessionUser().getUsername());
                yclMaterialOutEntity.setCreateTime(now_time);
                yclMaterialOutEntity.setBoxAmount((String) map.get("package"));
                yclMaterialOutEntityList.add(yclMaterialOutEntity);

                YclInOutFlowEntity yclInOutFlowEntity = new YclInOutFlowEntity();
                yclInOutFlowEntity.setStoreCode((String) map.get("fromSubinvCode"));
                yclInOutFlowEntity.setAreaCode(String.valueOf(map.get("organizationId")));
                yclInOutFlowEntity.setLocatorCode((String) map.get("locatorCode"));
                yclInOutFlowEntity.setMaterialCode((String) map.get("itemCode"));
                yclInOutFlowEntity.setLotsNum(lots_Num);
                yclInOutFlowEntity.setUpdownQuantity(new BigDecimal((String) map.get("outQuantity")));
                yclInOutFlowEntity.setInoutType("0");
                yclInOutFlowController.save(yclInOutFlowEntity);

                //是否自动调拨
                int flag = prodPickingDAO.checkItemCodeIfAutoMove((String) map.get("itemCode"));

                if (flag > 0) {
                    //是否自制库位
                    Map<String, Object> loc_map = prodPickingDAO.checkLocatorIsSelf(
                            (String) map.get("fromSubinvCode"),
                            String.valueOf(map.get("organizationId")),
                            (String) map.get("locatorCode")
                    );
                    if (null != loc_map) {
                        TransferOrderEntity transferEntity = new TransferOrderEntity();
                        String id = new String();
                        id = String.valueOf(transferOrderDAO.getSequence());
                        String line_id = String.valueOf(transferOrderDAO.getSequence());
                        transferEntity.setId(id);
                        transferEntity.setTranCode(countService.getNextCount("DBDH"));
                        transferEntity.setTranType("3");
                        transferEntity.setFromAreaCode(String.valueOf(map.get("organizationId")));
                        transferEntity.setToAreaCode("261");
                        transferEntity.setFromStoreCode((String) map.get("fromSubinvCode"));
                        transferEntity.setToStoreCode("Y001");
                        transferEntity.setCreatorId(this.getSessionUser().getUsername());
                        transferEntity.setCreateTime(DateUtil.today());
                        transferEntity.setStatus("1");

                        transferOrderDAO.insert(transferEntity);

                        TransferOrderLineEntity transferOrderLineEntity = new TransferOrderLineEntity();
                        transferOrderLineEntity.setLineId(line_id);
                        transferOrderLineEntity.setFromLocator((String) map.get("locatorCode"));
                        transferOrderLineEntity.setToLocator(loc_map.get("TRANSFER_LOCATOR").toString());
                        transferOrderLineEntity.setTranId(id);
                        transferOrderLineEntity.setLineState("1");
                        transferOrderLineEntity.setUpdateTime(DateUtil.parseDateTime(DateUtil.now()));
                        transferOrderLineEntity.setMaterialCode((String) map.get("itemCode"));
                        transferOrderLineEntity.setMaterialName((String) map.get("itemDesc"));
                        transferOrderLineEntity.setLotsNum(lots_Num);
                        transferOrderLineEntity.setPrimaryUnit((String) map.get("primaryUomCode"));
                        transferOrderLineEntity.setOutQuantity((String) map.get("outQuantity"));
                        transferOrderLineEntity.setOperator(this.getSessionUser().getUsername());
                        List<TransferOrderLineEntity> transferOrderLineEntityList = new ArrayList<>();
                        transferOrderLineEntityList.add(transferOrderLineEntity);
                        transferOrderLineService.saveBatch(transferOrderLineEntityList);

                        YclInOutFlowEntity en = new YclInOutFlowEntity();
                        en.setAreaCode("261");
                        en.setStoreCode("Y001");
                        en.setLocatorCode(loc_map.get("TRANSFER_LOCATOR").toString());
                        en.setMaterialCode((String) map.get("itemCode"));
                        en.setMaterialName((String) map.get("itemDesc"));
                        en.setLotsNum(lots_Num);
                        en.setUpdownQuantity(new BigDecimal((String) map.get("outQuantity")));
                        en.setInoutType("1");
                        en.setCreateTime(DateUtil.date());
                        en.setCreateUser(getSessionUser().getUsername());

                        yclInOutFlowController.save(en);

                        //回传EBS
                        List<TransferOrderEntity> transferOrderEntityList = new ArrayList<>();
                        transferOrderEntityList.add(transferEntity);
                        Map<String, String> ret = transferOrderController.saveTransferOrder(transferOrderEntityList);
                        if ("E".equals(ret.get("retCode"))) {
                            map.put("result", false);
                            map.put("msg", ret.get("retMess"));
                            return map;
                        }
                    }
                }
            }
            boolean result = prodPickingService.saveBatch(yclMaterialOutEntityList);
            ret_map.put("result", result);
            ret_map.put("msg", result ? "保存成功！" : "保存失败！");
        } catch (Exception e){
            e.printStackTrace();
        }
        return ret_map;
     }

     /**
     * 跳转Grid列表页
     *
     * @return
     */
    @RequestMapping(value = "/toList")
    public ModelAndView toRewindList() {
        ModelAndView mv = this.getModelAndView();
        mv.addObject("operationCode", roleService.selectOperationByRoleId(2L, MenuConstant.warehouselist));
        mv.setViewName("techbloom2/production/picking/list");
        return mv;
    }

    /**
     * 打印页面
     * @return
     */
    @RequestMapping("/toPrint")
    @ResponseBody
    public ModelAndView toPrint() {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom2/production/picking/print");

        return mv;
    }

    /**
     * 打印页面
     * @return
     */
    @RequestMapping("/toPrintDv")
    @ResponseBody
    public ModelAndView toPrintDv() {
        Map<String, Object> paramsMap = getAllParameter();

        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom2/production/picking/printdv");

        return mv;
    }

    @RequestMapping(value = "/checkprintstats")
    @ResponseBody
    public Map<String, Object> checkprintstats() {
        Map<String, Object> paramsMap = getAllParameter();
        Map<String, Object> map = new HashMap<>(4);

        String mo_code = paramsMap.get("moCode").toString();

        String[] mo_codes = mo_code.split(",");
        for(String code : mo_codes){
            int del_count = prodPickingDAO.getDeliveryCountByMoCode(code);
            if(del_count > 0){
                map.put("code", -1);
                map.put("msg", "领料单：" + code + " 已打印配送单，不能重复打印");
                return map;
            }
        }

        map.put("code", 0);
        map.put("msg", null);
        return map;
    }

    /**
     * 获取Grid列表数据
     *
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/outlist")
    @ResponseBody
    public Map<String, Object> outlist() {
        Map<String, Object> paramsMap = getAllParameter();
        List<VWmsShopItemReqEntity> pageList = prodPickingDAO.getOutPageList(
                paramsMap);
        Map<String, Object> map = new HashMap<>(4);
        map.put("code", 0);
        map.put("msg", null);
        map.put("count", pageList.size());
        map.put("data", pageList);
        return map;
    }

    /**
     * 获取Grid列表数据
     *
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/printList")
    @ResponseBody
    public Map<String, Object> printlist() {
        Map<String, Object> paramsMap = getAllParameter();
        List<VWmsShopItemReqEntity> pageList = prodPickingDAO.getPrintPageList(
                paramsMap);
        Map<String, Object> map = new HashMap<>(4);
        map.put("code", 0);
        map.put("msg", null);
        map.put("count", pageList.size());
        map.put("data", pageList);
        return map;
    }

    /**
     * 获取Grid列表数据
     *
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/printListDv")
    @ResponseBody
    public Map<String, Object> printlistDv() {
        Map<String, Object> paramsMap = getAllParameter();
        Map<String, Object> map = new HashMap<>(4);

        String mo_code = null == paramsMap.get("moCode")?"":paramsMap.get("moCode").toString();
        String deliveryId = null == paramsMap.get("deliveryId")?"":paramsMap.get("deliveryId").toString();


        List<VWmsShopItemReqEntity> pageList = new ArrayList<VWmsShopItemReqEntity>();



        if(StringUtils.isBlank(mo_code)){
            pageList = prodPickingDAO.getPrintDvPageListById(deliveryId);

            VWmsShopItemReqEntity vWmsShopItemReqEntity = pageList.get(0);

            String orgName = vWmsShopItemReqEntity.getOrganizationName();

            map.put("code", 0);
            map.put("msg", null);
            map.put("count", pageList.size());
            map.put("data", pageList);
            map.put("psdh", deliveryId);
            map.put("orgName", orgName);
            map.put("applyUser", this.getSessionUser().getUsername());

        } else {
            String today_str = DateUtil.today().replaceAll("-", "");

            String[] mo_codes = mo_code.split(",");

            List<String> moCodes = StringUtils.stringToListString(mo_code);

            pageList = prodPickingDAO.getPrintDvPageList(moCodes);

            VWmsShopItemReqEntity vWmsShopItemReqEntity = pageList.get(0);

            String orgCode = vWmsShopItemReqEntity.getOrgCode();
            String orgName = vWmsShopItemReqEntity.getOrganizationName();

            String seq_no = countService.getNextCount("PSDH");

            String psdh = "PS" + orgCode + today_str + seq_no.substring(seq_no.length() - 4);

            for(String code : mo_codes){
                YclPickDeliveryRelEntity yclPickDeliveryRelEntity = new YclPickDeliveryRelEntity();
                yclPickDeliveryRelEntity.setMoCode(code);
                yclPickDeliveryRelEntity.setDeliveryId(psdh);
                yclPickDeliveryRelEntity.setDeliveryDate(today_str);
                prodPickingDAO.insertPickDeliveryRel(yclPickDeliveryRelEntity);
            }

            map.put("code", 0);
            map.put("msg", null);
            map.put("count", pageList.size());
            map.put("data", pageList);
            map.put("psdh", psdh);
            map.put("orgName", orgName);
            map.put("applyUser", this.getSessionUser().getUsername());
        }



        return map;
    }

    /**
     * 跳转编辑页
     *
     * @return
     */
    @RequestMapping(value = "/toAddOut")
    public ModelAndView toDetail(String id) {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom2/production/picking/edit");
        return mv;
    }

    /**
     * 获取Grid列表数据
     *
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Map<String, Object> list() {
        Map<String, Object> paramsMap = getAllParameter();
        List<VWmsShopItemReqEntity> pageList = prodPickingDAO.getPageList(
                new Page(
                        Integer.parseInt((String) paramsMap.get("page")),
                        Integer.parseInt((String) paramsMap.get("limit"))),
                paramsMap);
        Map<String, Object> map = new HashMap<>(4);
        map.put("code", 0);
        map.put("msg", null);
        map.put("count", pageList.size());
        map.put("data", pageList);
        return map;
    }

    @RequestMapping(value = "/api/list")
    @ResponseBody
    public Map<String, Object> apiList() {
        Map<String, Object> paramsMap = getAllParameter();
        List<VWmsShopItemReqEntity> pageList = prodPickingDAO.getApiPageList(
                new Page(
                        Integer.parseInt((String) paramsMap.get("page")),
                        Integer.parseInt((String) paramsMap.get("limit"))),
                paramsMap);
        Map<String, Object> map = new HashMap<>(4);
        map.put("code", 0);
        map.put("msg", null);
        map.put("count", prodPickingDAO.countOfApi(paramsMap));
        map.put("data", pageList);
        return map;
    }

    @RequestMapping(value = "/yclOrderOut" ,method = {RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> yclOrderOut(@RequestBody YclOrderOutEntity yclOrderOutEntity) {
        Map<String,Object> paramsMap = new HashMap();
        Map<String,Object> resultMap = new HashMap();

        paramsMap.put("orderHeaderId",yclOrderOutEntity.getOrderNumber());
        paramsMap.put("requestCode",getUserId() ==  null ?"" :getUserId().toString());
        paramsMap.put("ruleName",yclOrderOutEntity.getRuleName());
        paramsMap.put("orgId",Long.parseLong(yclOrderOutEntity.getFactoryCode().toString()));

        yclMeterialOutDAO.yclOrderOut(paramsMap);
        if(paramsMap.containsKey("retCode")){
            resultMap.put("retCode",paramsMap.get("retCode"));
            resultMap.put("retMess",paramsMap.get("retMess"));
        }
        return resultMap;
    }

    /**
     * 接口描述: 获取批次号
     * @param entityId
     * @return
     */
    @RequestMapping(value = "/lotsnum/{entityId}/{warehouseId}/{itemCode}",method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getStoreList(@PathVariable("entityId") String entityId,
                                            @PathVariable("warehouseId") String warehouseId,
                                            @PathVariable("itemCode") String itemCode) {
        List<Map<String,Object>> list = prodPickingDAO.getLotsNumByEntityId(entityId, warehouseId, itemCode);
        if(list.size()>0){
            return restfulResponse(list);
        }else{
            return restfulResponseError();
        }
    }

    @RequestMapping(value = "/api/pickdetail" ,method = {RequestMethod.POST})
    @ResponseBody
    public List<Map<String, Object>> getPickDetailInfo(){
        List<Map<String,Object>> ret_list = new ArrayList<>();
        Map<String, Object> paramsMap = getAllParameter();

        String mo_code = paramsMap.get("moCode").toString();

        List<String> moCodes = StringUtils.stringToListString(mo_code);

        List<Map<String, Object>> fac_list = prodPickingDAO.queryFactFromMoCode(moCodes);

        if(fac_list.size() > 0) {

            for (Map<String, Object> map : fac_list) {
                String fac_code = map.get("FAC_CODE").toString();

                List<Map<String, Object>> item_list = prodPickingDAO.getPickDetailInfo(moCodes, fac_code);

                map.put("data_list", item_list);

                for(Map<String, Object> item : item_list){
                    String item_code = item.get("ITEM_CODE").toString();

                    List<Map<String, Object>> device_list = prodPickingDAO.getPickDeviceInfo(moCodes, fac_code, item_code);

                    item.put("device_list", device_list);
                }
            }
        }

        return ret_list;
    }

    @RequestMapping(value = "/deleteorder")
    @ResponseBody
    public Map<String, Object> deleteorder() {
        Map<String, Object> paramsMap = getAllParameter();
        Map<String, Object> map = new HashMap<>(4);

        String line_ids = paramsMap.get("line_ids").toString();

        String[] _line_ids = line_ids.split(",");
        for(String line_id : _line_ids){
            YclPickOrderBacklEntity yclPickOrderBacklEntity = new YclPickOrderBacklEntity();

            yclPickOrderBacklEntity.setLineId(line_id);
            yclPickOrderBacklEntity.setInsertDate(DateUtil.toLocalDateTime(new Date()));
            prodPickingDAO.insertPickOrderBack(yclPickOrderBacklEntity);
        }

        map.put("result", true);
        map.put("msg", "操作成功");
        return map;
    }

    /**
     * 单个领料单号汇总接口
     * @param str
     * @return
     */
    @RequestMapping(value = "/singleList",method =RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getSingleList(String outCode) {
//        JSONObject jsonObject1 = JSONObject.parseObject(str);
//        String outCode = String.valueOf(jsonObject1.get("outCode"));
        Map<String,Object> resultMap = new HashMap<>();
        List<Map<String,Object>> factoryList = new ArrayList<>();
        List<Map<String,Object>> materialList = new ArrayList<>();
        List<Map<String,Object>> machineList = new ArrayList<>();
        List<Map<String,Object>> factoryListResult = new ArrayList<>();
        Map<String,Object> tempMap = new HashMap<>();
        factoryList = prodPickingDAO.getPickingOutFactory(outCode);
        if(factoryList.size() >0){
            for(Map factory:factoryList){
                List<Map<String,Object>> materialListResult  = new ArrayList<>();
                Map factoryMap = new HashMap();
                //获取factoryName
                String areaCode = factory.get("AREA_CODE").toString();
                List<Map<String,Object>> factoryNameMap = prodPickingDAO.getPickingFactoryName(areaCode);
                String factoryName =factoryNameMap.get(0).get("ENTITYNAME").toString();
                factoryMap.put("factoryName",factoryName);
                //获取materialList
                Map paramMap = new HashMap();
                paramMap.put("code",outCode);
                paramMap.put("areaCode",areaCode);
                materialList = prodPickingDAO.getPickingOutMaterial(paramMap);
                for(Map material : materialList){
                    List<Map<String,Object>> machineListResult  = new ArrayList<>();
                    Map materialMap = new HashMap();
                    materialMap.put("materialCode",material.get("MATERIAL_CODE"));
                    materialMap.put("materialName",material.get("MATERIAL_NAME"));
                    materialMap.put("quantity",material.get("ZONGA"));
                    materialMap.put("boxAmount",material.get("ZONGAA"));
                    materialMap.put("primaryUnit",material.get("PRIMARY_UNIT"));
                    String materialCode = material.get("MATERIAL_CODE").toString();
                    //获取machineList
                    Map paramMap2 = new HashMap();
                    paramMap2.put("code",outCode);
                    paramMap2.put("areaCode",areaCode);
                    paramMap2.put("materialCode",materialCode);
                    machineList = prodPickingDAO.getPickingOutMachine(paramMap2);
                    for(Map machine:machineList){
                        Map machineMap = new HashMap();
                        machineMap.put("device",machine.get("DEVICE"));
                        machineMap.put("quantity",machine.get("ZONGB"));
                        machineListResult.add(machineMap);
                    }
                    Object  data3 = JSONObject.toJSON(machineListResult);
                    materialMap.put("devices",data3);
                    materialListResult.add(materialMap);
                }
                Object  data2 = JSONObject.toJSON(materialListResult);
                factoryMap.put("materials",data2);
                factoryListResult.add(factoryMap);
            }
            Object  data1 = JSONObject.toJSON(factoryListResult);
            tempMap.put("factorys",data1);
        }
        resultMap.put("result","1");
        resultMap.put("code","操作成功");
        resultMap.put("data",tempMap);
        return resultMap;
    }

    /**
     * 完成处理
     */
    @RequestMapping(value = "/outDeal",method =RequestMethod.PUT)
    @ResponseBody
    public Map<String,Object> outDeal(@RequestBody PickingOutDealEntity paramsEntity) {
        Map<String,Object> resultMap = new HashMap<>();
        //通过outCode获取area Code 和 storeCode
        String outCode = paramsEntity.getOutcode();
        Map paramsMap = (prodPickingDAO.getMaterialSite(outCode)).get(0);
        String material_code="";
        List<PickingOutItemEntity> itemList = paramsEntity.getItem();
        int box_amount=0;
        int qualityinfo = 0;
        try{
            for(PickingOutItemEntity item : itemList){
                paramsMap.put("locatorCode",item.getLocatorCode());
                paramsMap.put("materialCode",item.getMaterialCode());
                paramsMap.put("materialName",item.getMaterialName());
                material_code = item.getMachineCode() ;
                paramsMap.put("machineCode",material_code);
                paramsMap.put("lotsNum",item.getLotsNum());
                paramsMap.put("quantity",item.getQuantity());
                paramsMap.put("areaCode",paramsMap.get("AREA_CODE"));
                paramsMap.put("storeCode",paramsMap.get("STORE_CODE"));
                paramsMap.put("primaryUnit",paramsMap.get("PRIMARY_UNIT"));

                //判断是否为粒子料
                List<Map<String,Object>>  lizi= prodPickingDAO.getLiziInfo(material_code);
                if(lizi!=null)
                {
                    if(lizi.size()>0)
                    {
                        BigDecimal  t = item.getQuantity() ;
                        qualityinfo =t.intValue() ;
                        box_amount= (int)Math.ceil((double)qualityinfo/25);

                        qualityinfo= box_amount*25 ;
                        paramsMap.put("quantity",qualityinfo);
                        paramsMap.put("box_amount",box_amount);
                        prodPickingDAO.updateMaterialLiziQty(paramsMap);
                    }
                    else
                    {
                        prodPickingDAO.updateMaterialQty(paramsMap);
                    }
                }
                else
                {
                    prodPickingDAO.updateMaterialQty(paramsMap);
                }

                prodPickingDAO.updateInvetoryQty(paramsMap);
                YclInOutFlowEntity inOutFlowEntity = new YclInOutFlowEntity();
                inOutFlowEntity.setBusinessCode(outCode);
                inOutFlowEntity.setBusinessType("1");
                inOutFlowEntity.setInoutType("1");
                inOutFlowEntity.setLotsNum(String.valueOf(paramsMap.get("lotsNum")));
                inOutFlowEntity.setQuantity(new BigDecimal(paramsMap.get("quantity").toString()));
                inOutFlowEntity.setMaterialCode(String.valueOf(paramsMap.get("materialCode")));
                inOutFlowEntity.setMaterialName(String.valueOf(paramsMap.get("materialName")));
                inOutFlowEntity.setLocatorCode(String.valueOf(paramsMap.get("locatorCode")));
                inOutFlowEntity.setPrimaryUnit(String.valueOf(paramsMap.get("primaryUnit")));
                inOutFlowEntity.setAreaCode(String.valueOf(paramsMap.get("areaCode")));
                inOutFlowEntity.setStoreCode(String.valueOf(paramsMap.get("storeCode")));
                yclInOutFlowService.save(inOutFlowEntity);
            }
        }catch(Exception e) {
            e.printStackTrace();
            resultMap.put("result","-1");
            resultMap.put("code","保存失败，请联系系统管理员");
            return resultMap;
        }

        resultMap.put("result","1");
        resultMap.put("code","领料成功");
        return resultMap;
    }
}


